package com.company.test32;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

/**
 * Created by v on 16-12-8.
 */
public class CourseWithActionEvent {
    private String coutseName;
    private ArrayList<String> students;
    private int enrollmentCap;

    private ArrayList<ActionListener> actionListeners;

    public CourseWithActionEvent(){
        this(null);
    }

    public CourseWithActionEvent(String coutseName){
        this.coutseName=coutseName;
        enrollmentCap=10;
        students=new ArrayList<>();
        actionListeners=new ArrayList<>(2);
    }

    public String getCoutseName() {
        return coutseName;
    }

    public void addStudent(String student){
        students.add(student);
        if(students.size()>enrollmentCap){
            processEvent(new ActionEvent(this,
                    ActionEvent.ACTION_PERFORMED,null));
        }
    }

    public String[] getStudents() {
        return (String[]) students.toArray();
    }

    public int getEnrollmentCap() {
        return enrollmentCap;
    }

    public int getNumberOfStudent(){
        return students.size();
    }

    public void setEnrollmentCap(int enrollmentCap) {
        this.enrollmentCap = enrollmentCap;
    }

    public void addActionListener(ActionListener listener){
        if(!actionListeners.contains(listener)){
            actionListeners.add(listener);
        }
    }

    public void removeActionListener(ActionListener listener){
        if(actionListeners.contains(listener)){
            actionListeners.remove(listener);
        }
    }

    protected void processEvent(ActionEvent e){
        ArrayList<ActionListener> list;

        synchronized (this){
            list=(ArrayList<ActionListener>) actionListeners.clone();
        }

        for(int i=0;i<list.size();i++){
            ActionListener listener=list.get(i);
            listener.actionPerformed(e);
        }
    }
}
